package com.restkeeper.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.restkeeper.entity.OrderDetailEntity;
import com.restkeeper.entity.OrderEntity;
import com.restkeeper.exception.BussinessException;
import com.restkeeper.response.page.PageVO;
import com.restkeeper.service.IOrderService;
import com.restkeeper.store.entity.Table;
import com.restkeeper.store.entity.TableLog;
import com.restkeeper.store.service.ITableAreaService;
import com.restkeeper.store.service.ITableLogService;
import com.restkeeper.store.service.ITableService;
import com.restkeeper.utils.SystemCode;
import com.restkeeper.vo.OrderDetailVO;
import com.restkeeper.vo.OrderVO;
import com.restkeeper.vo.TablePanelVO;
import com.restkeeper.vo.TableVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/table")
@Api(tags = {"收银端区域桌台接口"})
public class TableController {

    @Reference(version = "1.0.0", check=false)
    private ITableAreaService tableAreaService;

    @Reference(version = "1.0.0", check=false)
    private ITableLogService tablelogService;

    @Reference(version = "1.0.0", check=false)
    private ITableService tableService;

    @Reference(version = "1.0.0", check=false)
    private IOrderService orderService;

    @ApiOperation(value = "区域列表接口")
    @GetMapping("/listTableArea")
    public List<Map<String,Object>> list(){
        return tableAreaService.listTableArea();
    }

    @ApiOperation(value = "开桌")
    @PutMapping("/openTable/{tableId}/numbers/{numbers}")
    public boolean openTable(@PathVariable String tableId, @PathVariable Integer numbers){
        TableLog tableLog =new TableLog();
        tableLog.setTableId(tableId);
        tableLog.setUserNumbers(numbers);
        return tablelogService.openTable(tableLog);
    }

    @ApiOperation(value = "预定/释放/清台 2 预定 0 释放 清台")
    @PutMapping("/{tableId}/{status}")
    public boolean operate(@PathVariable String tableId, @PathVariable Integer status){
        if(SystemCode.TABLE_STATUS_LOCKED==status){
          return tableService.lockTable(tableId);
        }
        if(SystemCode.TABLE_STATUS_FREE==status){
            return tableService.releaseTable(tableId);
        }
       throw  new BussinessException("不支持该状态操作");
    }


    @ApiOperation(value = "桌台面板")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "path", name = "areaId", value = "区域Id", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "path", name = "page", value = "页码", required = true, dataType = "Long"),
            @ApiImplicitParam(paramType = "path", name = "pageSize", value = "每页数量", required = true, dataType = "Long")})
    @GetMapping("/search/{areaId}/{page}/{pageSize}")
    public TablePanelVO queryByArea(@PathVariable String areaId, @PathVariable long page, @PathVariable long pageSize){
        TablePanelVO tablePanelVO=new TablePanelVO();
        //桌台统计信息
        tablePanelVO.setFreeNumbers(tableService.countTableByStatus(areaId, SystemCode.TABLE_STATUS_FREE));
        tablePanelVO.setOpenedNumbers(tableService.countTableByStatus(areaId, SystemCode.TABLE_STATUS_OPEND));
        tablePanelVO.setLockedNumbers(tableService.countTableByStatus(areaId, SystemCode.TABLE_STATUS_LOCKED));
        //桌台面板详情，支持分页
        IPage<Table> pageTable= tableService.queryPageByArea(areaId,page,pageSize);
        List<TableVO> tablevoList =new ArrayList<>();
        pageTable.getRecords().forEach(d->{
            TableVO tableVO=new TableVO();
            tableVO.setTableId(d.getTableId());
            tableVO.setTableName(d.getTableName());
            tableVO.setStatus(d.getStatus());
            tableVO.setSeatNumber(d.getSeatNumber());
            //如果开桌状态
            if(SystemCode.TABLE_STATUS_OPEND==d.getStatus()){
                //从table_log读取时间 及开桌人数
                TableLog tableLog = tablelogService.getOpenTableLog(d.getTableId());
                if(tableLog!=null){
                    tableVO.setCreateTime(tableLog.getCreateTime());
                    tableVO.setUserNumbers(tableLog.getUserNumbers());
                }
            }
            tablevoList.add(tableVO);
        });
        //PageVO 封装
        PageVO<TableVO> pageVO =new PageVO<>(pageTable,tablevoList);
        tablePanelVO.setTablePage(pageVO);
        return tablePanelVO;
    }

    /**
     * 换桌
     * @param tableId
     * @param targetTableId
     * @return
     */
    @ApiOperation(value = "换桌")
    @PutMapping("/changeTable/{tableId}/{targetTableId}")
    public boolean changeTable(@PathVariable String tableId,@PathVariable String targetTableId){
        return orderService.changeTable(tableId,targetTableId);
    }

    @ApiOperation(value = "修改人数")
    @PutMapping("/changeNumber/{tableId}/{number}")
    public boolean changeNumber(@PathVariable String tableId, @PathVariable Integer number){
        return orderService.changeNumber(tableId,number);
    }


    @ApiOperation(value = "根据桌台id获取订单")
    @GetMapping("/getOrders/{tableId}")
    public OrderVO getOrders(@PathVariable String tableId){
        OrderVO orderVO =new OrderVO();
        OrderEntity orderEntity= orderService.getNoPayOrder(tableId);
        //如果没有下单，订单没有，从日志表从新构造
        if(orderEntity==null){
            TableLog tableLog = tablelogService.getOpenTableLog(tableId);
            if(tableLog!=null){
                orderVO.setPersonNumbers(tableLog.getUserNumbers());
                orderVO.setTableId(tableId);
            }
        }else{
            BeanUtils.copyProperties(orderEntity,orderVO);
            if(StringUtils.isNoneBlank(orderEntity.getOrderRemark())){
                String orderRemark =orderEntity.getOrderRemark();
                orderRemark=orderRemark.substring(orderRemark.indexOf("[")+1,orderRemark.indexOf("]"));
                if(StringUtils.isNotEmpty(orderRemark)){
                    String[] orderRemark_array= orderRemark.split(",");
                    orderVO.setOrderRemark(Arrays.asList(orderRemark_array));
                }
            }
            List<OrderDetailEntity>  orderDetailEntityList= orderEntity.getOrderDetails();
            if(orderDetailEntityList!=null){
                Integer payAmount=0;
                List<OrderDetailVO> list=new ArrayList<>();
                for (OrderDetailEntity orderDetailEntity : orderDetailEntityList) {
                    //后端计算应付款金额
                    if(orderDetailEntity.getDetailStatus()==1||orderDetailEntity.getDetailStatus()==4){
                        payAmount+=orderDetailEntity.getDishPrice()*orderDetailEntity.getDishNumber();
                    }
                    OrderDetailVO orderDetailVO =new OrderDetailVO();
                    BeanUtils.copyProperties(orderDetailEntity, orderDetailVO);
                    orderDetailVO.setPrice(orderDetailEntity.getDishPrice());
                    orderDetailVO.setStatus(orderDetailEntity.getDetailStatus());
                    String flavorRemark= orderDetailEntity.getFlavorRemark();
                    flavorRemark=flavorRemark.substring(flavorRemark.indexOf("[")+1,flavorRemark.indexOf("]"));
                    if(StringUtils.isNotEmpty(flavorRemark)){
                        String[] flavorRemark_array= flavorRemark.split(",");
                        orderDetailVO.setFlavorList(Arrays.asList(flavorRemark_array));
                    }
                    list.add(orderDetailVO);
                }
                orderVO.setPayAmount(payAmount);
                orderVO.setDishs(list);
            }
        }
        return orderVO;
    }

//    @ApiOperation(value = "根据桌台id获取订单")
//    @GetMapping("/getOrders/{tableId}")
//    public OrderEntity getOrders(@PathVariable String tableId){
//        return orderService.getNoPayOrder(tableId);
//    }

}
